package com.chaihu.api.listener.user.login;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.chaihu.api.listener.AbstractServiceApiListener;
import com.chaihu.bean.entity.common.TokenInfoDto;
import com.chaihu.bean.enums.MsgCode;
import com.chaihu.bean.in.user.userinfo.QueryUserIn;
import com.chaihu.bean.out.user.userinfo.QueryUserOut;
import com.chaihu.bean.result.ResponseResult;
import com.chaihu.core.annotation.ChaihuListener;
import com.chaihu.core.context.DataFlowContext;
import com.chaihu.core.event.service.api.ServiceDataFlowEvent;
import com.chaihu.core.factory.AuthenticationFactory;
import com.chaihu.intf.user.QueryUsersService;
import com.chaihu.utils.constant.ServiceCodeConstant;
import com.chaihu.utils.util.Assert;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * 用户注册 侦听
 * Created by wuxw on 2018/5/18.
 */
@Slf4j
@ChaihuListener("loginPcAccountServiceListener")
public class LoginPcAccountServiceListener extends AbstractServiceApiListener {

    @Autowired
    private QueryUsersService queryUsersService;

    @Override
    protected void validate(ServiceDataFlowEvent event, JSONObject reqJson) {
        log.info("========= json 入参：{}", reqJson.toJSONString());

        Assert.hasKeyAndValue(reqJson, "account", "未包含account");
        Assert.hasKeyAndValue(reqJson, "passwd", "未包含passwd");
        Assert.hasKeyAndValue(reqJson, "channelNo", "未包含channelNo");
    }

    @Override
    protected void doSoService(ServiceDataFlowEvent event, DataFlowContext context, JSONObject reqJson) {
        String account = reqJson.getString("account");
        String passwd = reqJson.getString("passwd");
        String channelNo = reqJson.getString("channelNo");

        JSONObject userInfo = new JSONObject();

        // 根据账号Account和passwd查询用户信息
        QueryUserIn queryUserIn = new QueryUserIn();
        queryUserIn.setAccount(account);
        queryUserIn.setPassword(passwd);
        ResponseResult<List<QueryUserOut>> queryUsersResponseResult = queryUsersService.queryUsers(queryUserIn);
        if (!StringUtils.equals(MsgCode.SUCCESS.getCode(), queryUsersResponseResult.getCode()) || CollectionUtils.isEmpty(queryUsersResponseResult.getData())) {
            ResponseEntity<String> responseEntity = new ResponseEntity<>(JSONObject.toJSONString(queryUsersResponseResult), HttpStatus.OK);
            context.setResponseEntity(responseEntity);
            return;
        }
        QueryUserOut queryUserOut = queryUsersResponseResult.getData().get(0);

        if (queryUserOut == null) {
            ResponseResult responseResult = new ResponseResult(MsgCode.ERROR.getCode(), "账号或密码错误");
            ResponseEntity responseEntity = new ResponseEntity<String>(JSON.toJSONString(responseResult), HttpStatus.OK);
            context.setResponseEntity(responseEntity);
            return;
        }

        ResponseEntity responseEntity= null;
        try {
            // pc后台登录
            TokenInfoDto tokenInfoDto = new TokenInfoDto(queryUserOut.getUserId(), channelNo, queryUserOut.getName(), queryUserOut.getMobile());
            String token = AuthenticationFactory.createAndSaveToken(tokenInfoDto, AuthenticationFactory.COMMUNITY_TOKEN_SESSION_EXPIRE_TIME + "");

            userInfo.put("userName", queryUserOut.getName());
            userInfo.put("userId", queryUserOut.getUserId());
            userInfo.remove("userPwd");
            userInfo.put("token", token);
            responseEntity = new ResponseEntity<String>(userInfo.toJSONString(), HttpStatus.OK);
        } catch (Exception e) {
            log.error("登录异常：", e);
            ResponseResult responseResult = new ResponseResult(MsgCode.ERROR.getCode(), "系统内部错误，请联系管理员");
            responseEntity = new ResponseEntity<String>(JSON.toJSONString(responseResult), HttpStatus.OK);
        }
        context.setResponseEntity(responseEntity);
    }

    @Override
    public String getServiceCode() {
        return ServiceCodeConstant.SERVICE_CODE_USER_SERVICE_PC_ACCOUNT_LOGIN;
    }

    @Override
    public HttpMethod getHttpMethod() {
        return HttpMethod.POST;
    }
}
